package com.christina.service.application;

import com.alibaba.fastjson.JSONObject;
import com.christina.engine.intent.IntentRecognitionEngine;
import com.christina.engine.intent.model.Intent;
import com.christina.engine.context.ContextManager;
import com.christina.engine.decision.DecisionEngine;
import com.christina.engine.decision.model.DecisionResult;
import com.christina.service.domain.travel.TravelDomainService;
import com.christina.service.domain.chat.ChatDomainService;
import com.christina.service.domain.user.UserDomainService;
import com.christina.service.application.model.UnifiedRequest;
import com.christina.service.application.model.UnifiedResponse;
import com.christina.service.application.model.UnifiedResponse.UnifiedResponseBuilder;
import com.christina.engine.processing.RequestProcessorChain;
import com.christina.engine.processing.model.ProcessingContext;
import com.christina.engine.processing.model.ProcessingResult;
import com.christina.engine.observer.EventManager;
import com.christina.engine.observer.ProcessingEvent;
import com.christina.engine.singleton.ConfigurationManager;
import com.christina.engine.state.ConversationStateManager;
import com.christina.engine.state.model.StateContext;
import com.christina.engine.state.model.StateTransitionResult;
import com.christina.engine.response.decorator.ResponseDecorator;
import com.christina.engine.response.model.ResponseContext;
import com.christina.engine.response.model.ResponseResult;
import com.christina.service.domain.travel.model.TravelPlanRequest;
import com.christina.service.domain.chat.model.ChatRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Christina统一应用服务
 * 这是系统的核心协调器，负责整合AI引擎和各个领域服务
 * 现已完全集成9种设计模式，提供高性能、可扩展的智能服务
 *
 * @author Christina
 */
@Slf4j
@Service
public class ChristinaApplicationService {

    // 传统组件（保持兼容性）
    private final IntentRecognitionEngine intentEngine;
    private final ContextManager contextManager;
    private final DecisionEngine decisionEngine;
    private final TravelDomainService travelDomainService;
    private final ChatDomainService chatDomainService;
    private final UserDomainService userDomainService;

    // 新设计模式组件
    private final RequestProcessorChain requestProcessorChain;
    private final EventManager eventManager;
    private final ConfigurationManager configurationManager;
    private final ConversationStateManager conversationStateManager;
    private final List<ResponseDecorator> responseDecorators;

    @Autowired
    public ChristinaApplicationService(
            IntentRecognitionEngine intentEngine,
            ContextManager contextManager,
            DecisionEngine decisionEngine,
            TravelDomainService travelDomainService,
            ChatDomainService chatDomainService,
            UserDomainService userDomainService,
            RequestProcessorChain requestProcessorChain,
            EventManager eventManager,
            ConversationStateManager conversationStateManager,
            List<ResponseDecorator> responseDecorators) {
        this.intentEngine = intentEngine;
        this.contextManager = contextManager;
        this.decisionEngine = decisionEngine;
        this.travelDomainService = travelDomainService;
        this.chatDomainService = chatDomainService;
        this.userDomainService = userDomainService;
        this.requestProcessorChain = requestProcessorChain;
        this.eventManager = eventManager;
        this.configurationManager = ConfigurationManager.getInstance();
        this.conversationStateManager = conversationStateManager;
        this.responseDecorators = responseDecorators;
    }

    /**
     * 统一处理用户请求 - 新架构主入口
     * 完全基于设计模式的处理流程
     */
    public UnifiedResponse processRequest(UnifiedRequest request) {
        String requestId = generateRequestId();
        log.info("开始处理用户请求: requestId={}, userId={}, input={}",
                requestId, request.getUserId(), request.getUserInput());

        // 发布请求接收事件
        publishEvent(ProcessingEvent.createRequestEvent(
                        ProcessingEvent.EventType.REQUEST_RECEIVED,
                        "ChristinaApplicationService",
                        request.getSessionId())
                .addEventData("userId", request.getUserId())
                .addEventData("requestId", requestId));

        try {
            // 检查是否启用新架构
            boolean newArchitectureEnabled = configurationManager.getBoolean("design-patterns.enabled", true);

            if (newArchitectureEnabled) {
                return processWithNewArchitecture(request, requestId);
            } else {
                return processWithLegacyArchitecture(request, requestId);
            }

        } catch (Exception e) {
            log.error("请求处理失败: requestId={}, userId={}", requestId, request.getUserId(), e);

            // 发布错误事件
            publishEvent(ProcessingEvent.createErrorEvent(
                    "ChristinaApplicationService",
                    e.getMessage(),
                    request.getSessionId()));

            return UnifiedResponse.builder()
                    .success(false)
                    .errorMessage("处理请求时发生错误: " + e.getMessage())
                    .requestId(requestId)
                    .timestamp(LocalDateTime.now())
                    .processingTime(0L)
                    .build();
        }
    }

    /**
     * 使用新架构处理请求（基于设计模式）
     */
    private UnifiedResponse processWithNewArchitecture(UnifiedRequest request, String requestId) {
        try {
            // 1. 创建处理上下文
            ProcessingContext context = createProcessingContext(request, requestId);

            // 2. 使用责任链处理请求
            ProcessingResult result = requestProcessorChain.process(context);

            // 3. 应用响应装饰器
            UnifiedResponse response = buildResponseFromContext(context, result);
            response = applyResponseDecorators(response, context);

            // 4. 更新对话状态
            updateConversationState(request, response);

            // 5. 发布处理完成事件
            publishEvent(ProcessingEvent.createRequestEvent(
                            ProcessingEvent.EventType.REQUEST_COMPLETED,
                            "ChristinaApplicationService",
                            request.getSessionId())
                    .addEventData("requestId", requestId)
                    .addEventData("success", result.isSuccess())
                    .addEventData("processingTime", System.currentTimeMillis()));

            log.info("新架构请求处理完成: requestId={}, success={}", requestId, result.isSuccess());
            return response;

        } catch (Exception e) {
            log.error("新架构处理失败: requestId={}", requestId, e);
            throw e;
        }
    }

    /**
     * 使用传统架构处理请求（兼容性保证）
     */
    private UnifiedResponse processWithLegacyArchitecture(UnifiedRequest request, String requestId) {
        log.info("使用传统架构处理请求: requestId={}", requestId);

        try {
            // 使用传统的处理流程
            // 1. 意图识别
            Intent intent = intentEngine.recognizeIntent(request.getUserInput(), null);

            // 2. 决策分析
            DecisionResult decision = decisionEngine.makeDecision(null);

            // 3. 执行服务
            String content = "传统架构处理结果: " + request.getUserInput();

            return UnifiedResponse.builder()
                    .success(true)
                    .content(content)
                    .requestId(requestId)
                    .timestamp(LocalDateTime.now())
                    .intent(intent)
                    .decisionResult(decision)
                    .processingTime(50L) // 模拟处理时间
                    .build();

        } catch (Exception e) {
            log.error("传统架构处理失败: requestId={}", requestId, e);
            return UnifiedResponse.builder()
                    .success(false)
                    .content(null)
                    .errorMessage("传统架构处理失败: " + e.getMessage())
                    .requestId(requestId)
                    .timestamp(LocalDateTime.now())
                    .processingTime(0L)
                    .build();
        }
    }

    /**
     * 创建处理上下文
     */
    private ProcessingContext createProcessingContext(UnifiedRequest request, String requestId) {
        return ProcessingContext.builder()
                .requestId(requestId)
                .originalRequest(request)
                .userId(request.getUserId())
                .sessionId(request.getSessionId())
                .responseBuilder(UnifiedResponse.builder()
                        .requestId(requestId)
                        .timestamp(LocalDateTime.now()))
                .build();
    }

    /**
     * 从处理上下文构建统一响应
     */
    private UnifiedResponse buildResponseFromContext(ProcessingContext context, ProcessingResult result) {
        UnifiedResponseBuilder responseBuilder = context.getResponseBuilder();

        // 设置处理结果状态
        responseBuilder.success(result.isSuccess());

        // 设置响应内容
        if (result.isSuccess() && result.getResultData() != null) {
            Object resultContent = result.getResultData().get("content");
            if (resultContent != null) {
                responseBuilder.content(resultContent.toString());
            } else {
                responseBuilder.content("处理完成");
            }
        }

        // 如果处理失败，设置错误信息
        if (!result.isSuccess()) {
            responseBuilder.errorMessage(result.getErrorMessage());
        }

        // 从上下文中获取识别到的意图
        Intent recognizedIntent = context.getRecognizedIntent();
        if (recognizedIntent != null) {
            responseBuilder.intent(recognizedIntent);
        }

        // 从上下文中获取决策结果
        DecisionResult decisionResult = context.getDecisionResult();
        if (decisionResult != null) {
            responseBuilder.decisionResult(decisionResult);
        }

        // 从上下文中获取业务执行结果
        if (context.getProcessingData() != null) {
            Object businessResult = context.getProcessingData().get("executionResult");
            if (businessResult != null) {
                responseBuilder.businessResult(businessResult);
            }
        }

        // 设置处理时间
        long processingTime = java.time.Duration.between(context.getStartTime(), LocalDateTime.now()).toMillis();
        responseBuilder.processingTime(processingTime);

        return responseBuilder.build();
    }

    /**
     * 应用响应装饰器
     */
    private UnifiedResponse applyResponseDecorators(UnifiedResponse response, ProcessingContext context) {
        if (responseDecorators == null || responseDecorators.isEmpty()) {
            return response;
        }

        try {
            // 创建响应上下文
            ResponseContext responseContext = ResponseContext.builder()
                    .sessionId(context.getSessionId())
                    .userId(context.getUserId())
                    .requestId(context.getContextId())
                    .originalRequest(context.getOriginalRequest())
                    .build();

            // 创建响应结果
            Map<String, Object> metadata = new HashMap<>();
            metadata.put("processingTime", response.getProcessingTime());
            if (response.getIntent() != null) {
                metadata.put("intent", response.getIntent());
            }
            if (response.getDecisionResult() != null) {
                metadata.put("decisionResult", response.getDecisionResult());
            }

            ResponseResult responseResult = ResponseResult.builder()
                    .content(response.getContent())
                    .success(response.isSuccess())
                    .metadata(metadata)
                    .build();

            // 依次应用装饰器
            for (ResponseDecorator decorator : responseDecorators) {
                if (decorator.isEnabled()) {
                    responseResult = decorator.decorate(responseResult, responseContext);
                }
            }

            // 更新响应内容
            return response.toBuilder()
                    .content(responseResult.getContent())
                    .build();

        } catch (Exception e) {
            log.warn("应用响应装饰器失败", e);
            return response; // 返回原始响应
        }
    }

    /**
     * 更新对话状态
     */
    private void updateConversationState(UnifiedRequest request, UnifiedResponse response) {
        try {
            String sessionId = request.getSessionId();

            // 检查是否已有活跃的对话状态
            if (!conversationStateManager.hasSession(sessionId)) {
                // 创建新的对话会话
                StateContext stateContext = StateContext.builder()
                        .sessionId(sessionId)
                        .userId(request.getUserId())
                        .currentMessage(request.getUserInput())
                        .build();

                conversationStateManager.startSession(sessionId, "Initial", stateContext);
            } else {
                // 处理现有会话的消息
                StateTransitionResult stateResult = conversationStateManager.handleMessage(
                        sessionId, request.getUserInput());

                if (stateResult != null && stateResult.hasResponseMessage()) {
                    log.debug("状态管理器响应: {}", stateResult.getResponseMessage());
                }
            }

        } catch (Exception e) {
            log.warn("更新对话状态失败: sessionId={}", request.getSessionId(), e);
        }
    }

    /**
     * 发布事件
     */
    private void publishEvent(ProcessingEvent event) {
        try {
            eventManager.publishEventAsync(event);
        } catch (Exception e) {
            log.warn("发布事件失败: {}", event.getEventId(), e);
        }
    }

    /**
     * 生成请求ID
     */
    private String generateRequestId() {
        return "REQ_" + System.currentTimeMillis() + "_" + (int)(Math.random() * 1000);
    }

    /**
     * 获取系统统计信息
     */
    public Map<String, Object> getSystemStatistics() {
        Map<String, Object> stats = new HashMap<>();

        try {
            // 事件管理器统计
            stats.put("eventManager", eventManager.getStatistics());

            // 配置管理器统计
            stats.put("configurationManager", configurationManager.getStatistics());

            // 状态管理器统计
            stats.put("conversationStateManager", conversationStateManager.getStatistics());

            // 处理器链统计
            stats.put("requestProcessorChain", Map.of(
                    "processorCount", requestProcessorChain.getProcessorCount(),
                    "enabled", requestProcessorChain.isEnabled()
            ));

        } catch (Exception e) {
            log.error("获取系统统计信息失败", e);
            stats.put("error", "Failed to collect statistics: " + e.getMessage());
        }

        return stats;
    }

    /**
     * 健康检查
     */
    public Map<String, Object> healthCheck() {
        Map<String, Object> health = new HashMap<>();

        try {
            // 检查各个组件的健康状态
            health.put("status", "UP");
            health.put("timestamp", LocalDateTime.now());

            // 检查责任链处理器
            health.put("processorChain", Map.of(
                    "enabled", requestProcessorChain.isEnabled(),
                    "processorCount", requestProcessorChain.getProcessorCount()
            ));

            // 检查事件系统
            health.put("eventSystem", Map.of(
                    "queueSize", eventManager.getEventQueueSize(),
                    "listenerCount", eventManager.getAllListeners().size()
            ));

            // 检查状态管理
            health.put("stateManagement", Map.of(
                    "activeSessions", conversationStateManager.getActiveSessionIds().size()
            ));

            // 检查配置管理
            health.put("configurationManagement", Map.of(
                    "version", configurationManager.getConfigVersion(),
                    "totalConfigs", configurationManager.getAllConfigurations().size()
            ));

        } catch (Exception e) {
            log.error("健康检查失败", e);
            health.put("status", "DOWN");
            health.put("error", e.getMessage());
        }

        return health;
    }

    /**
     * 清理会话资源
     */
    public void cleanupSession(String sessionId) {
        try {
            // 结束对话状态
            if (conversationStateManager.hasSession(sessionId)) {
                conversationStateManager.endSession(sessionId, "Session cleanup");
            }

            // 发布会话清理事件
            publishEvent(ProcessingEvent.builder()
                    .eventType(ProcessingEvent.EventType.CUSTOM)
                    .source("ChristinaApplicationService")
                    .sessionId(sessionId)
                    .timestamp(LocalDateTime.now())
                    .build()
                    .addEventData("action", "session_cleanup"));

            log.info("会话资源清理完成: sessionId={}", sessionId);

        } catch (Exception e) {
            log.error("清理会话资源失败: sessionId={}", sessionId, e);
        }
    }

    /**
     * 重新加载配置
     */
    public void reloadConfiguration() {
        try {
            // 重置配置管理器
            configurationManager.resetToDefaults();

            // 发布配置重载事件
            publishEvent(ProcessingEvent.createSystemEvent(
                            ProcessingEvent.EventType.CUSTOM,
                            "ChristinaApplicationService")
                    .addEventData("action", "configuration_reload"));

            log.info("配置重载完成");

        } catch (Exception e) {
            log.error("重载配置失败", e);
            throw new RuntimeException("Failed to reload configuration", e);
        }
    }

    // ==================== 兼容性方法 ====================
    // 保留原有方法以确保向后兼容性

    /**
     * 执行目标服务（兼容性方法）
     */
    public Object executeTargetService(String targetService, Map<String, Object> parameters, UnifiedRequest request) {
        JSONObject jsonParameters = new JSONObject(parameters);

        return switch (targetService.toLowerCase()) {
            case "travel" -> executeTravelService(jsonParameters, request);
            case "chat" -> executeChatService(jsonParameters, request);
            case "user" -> executeUserService(jsonParameters, request);
            default -> {
                log.warn("未知的目标服务: {}", targetService);
                yield "抱歉，我无法识别您的需求，请重新描述。";
            }
        };
    }

    /**
     * 执行出行服务（兼容性方法）
     */
    private Object executeTravelService(JSONObject parameters, UnifiedRequest request) {
        try {
            // 使用建造者模式构建请求
            TravelPlanRequest travelRequest = com.christina.engine.parameter.builder.TravelPlanRequestBuilder.newBuilder()
                    .userId(request.getUserId())
                    .origin((String) parameters.getOrDefault("origin", ""))
                    .destination((String) parameters.getOrDefault("destination", ""))
                    .departureTime(parameters.containsKey("departureTime") ?
                            parameters.getString("departureTime") : null)
                    .passengerCount(parameters.containsKey("passengerCount") ?
                            ((Number) parameters.get("passengerCount")).intValue() : null)
                    .budget(parameters.containsKey("budget") ?
                            ((Number) parameters.get("budget")).doubleValue() : null)
                    .transportMode((String) parameters.getOrDefault("transportMode", "不限"))
                    .build();

            return travelDomainService.planTravel(travelRequest);

        } catch (Exception e) {
            log.error("执行出行服务失败", e);
            return "出行规划服务暂时不可用，请稍后重试。";
        }
    }

    /**
     * 执行聊天服务（兼容性方法）
     */
    private Object executeChatService(JSONObject parameters, UnifiedRequest request) {
        try {
            // 使用建造者模式构建请求
            ChatRequest chatRequest = com.christina.engine.parameter.builder.ChatRequestBuilder.newBuilder()
                    .userId(request.getUserId())
                    .sessionId(request.getSessionId())
                    .message(request.getUserInput())
                    .chatType("问答")
                    .language("zh-CN")
                    .build();

            return chatDomainService.processChat(chatRequest);

        } catch (Exception e) {
            log.error("执行聊天服务失败", e);
            return "聊天服务暂时不可用，请稍后重试。";
        }
    }

    /**
     * 执行用户服务（兼容性方法）
     */
    private Object executeUserService(JSONObject parameters, UnifiedRequest request) {
        try {
            String action = (String) parameters.getOrDefault("action", "profile");

            return switch (action) {
                case "profile" -> userDomainService.getUserContext(request.getUserId());
                case "preferences" -> userDomainService.updateUserPreferences(request.getUserId(), parameters);
                case "statistics" -> userDomainService.getUserStatistics(request.getUserId());
                default -> "用户服务功能正在完善中";
            };

        } catch (Exception e) {
            log.error("执行用户服务失败", e);
            return "用户服务暂时不可用，请稍后重试。";
        }
    }
}